package qs.openxt.libs.util;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.view.UIAlertView;

public class ActivityUtil {
	/**
	 * 判断网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
        if(context == null)
            return false;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
			return false;
		} else {
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

    /**
     * 显示确认对话框
     * @param message
     * @param listener
     */
    public static void showConfirmDialog(Context context, String message, String ok, String cancel, final ConfirmDialogListener listener) {
        final UIAlertView dialog = new UIAlertView.Builder(context)
                .setTitle("温馨提示")
                .setMessage(message)
                .setPositiveButton(ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (listener != null)
                            listener.onOK();
                    }
                }).setNegativeButton(cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (listener != null)
                            listener.onCancel();
                    }
                }).create();
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 获得系统版本号
     *
     * @return 系统版本号
     */
    public static String getVersion(Context context) {
        String version = "";
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo pinfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            version = pinfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }
}
